package com.example.controller;

import com.example.domain.BaseEntity;
import com.example.domain.Result;
import com.example.domain.Scholarship;
import com.example.domain.Student;
import com.example.service.ScholarshipService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sscholarship")
public class StudentScholarshipController extends MyController {

    @Autowired
    private ScholarshipService scholarshipService;

    @PostMapping("/list")
    public Result list(Scholarship scholarship, HttpSession session) {

        BaseEntity baseEntity = (BaseEntity) session.getAttribute("login");
        if (baseEntity instanceof Student) {
            Student student = (Student) baseEntity;
            Long studentId = student.getStudentId();
            scholarship.setStudentId(studentId);
        }
        PageInfo<Map> pageInfo = this.scholarshipService.selectPageList(scholarship);
        return success(pageInfo);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Long scholarshipId) {
        Scholarship scholarship = this.scholarshipService.selectById(scholarshipId);
        return success(scholarship);
    }

    @PostMapping("/save")
    public Result add(Scholarship scholarship, HttpSession session) {
        BaseEntity baseEntity = (BaseEntity) session.getAttribute("login");
        if (baseEntity instanceof Student) {
            Student student = (Student) baseEntity;
            Long studentId = student.getStudentId();
            scholarship.setStudentId(studentId);
            scholarship.setTrueName(student.getTrueName());
        }
        List<Map> scholarshipList = this.scholarshipService.selectListByAcademicYear(scholarship.getAcademicYear(), scholarship.getScholarshipId());
        if (scholarshipList.size() > 0) {
            return error("您已经申请过了");
        }
        scholarship.setStatus("初审中");
        scholarship.setLevel(null);
        this.scholarshipService.save(scholarship);
        return success();
    }

    @PostMapping("/del/{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        this.scholarshipService.deleteById(id);
        return success();
    }
}
